package com.javen.weixin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.javen.common.Contant;
import com.jfinal.template.ext.sharedmethod.Json;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import net.adetech.crj.dao.WechatMenu;
import net.adetech.crj.entity.WechatMenuBean;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class WeixinApiController extends ApiController {

	/**
	 * 获取公众号菜单
	 */
	public void getMenu() {
		ApiResult apiResult = MenuApi.getMenu();
		if (apiResult.isSucceed())
			renderText(apiResult.getJson());
		else
			renderText(apiResult.getErrorMsg());
	}

	/**
	 * 创建菜单
	 */
	public void createMenu()
	{

		JSONObject menuJson = new JSONObject();
		List<WechatMenu> wechatMenuList = WechatMenu.dao.find("select * from CRJ_WECHAT_MENU order by MENU_LEVEL,MENU_ORDER");

		List<WechatMenuBean> menuList = new LinkedList<>();
		Map<String,WechatMenuBean> menuMap = new HashMap<>();


		Map<String,String > mediaIdMap = this.getMediaIdList();

		for (WechatMenu menu : wechatMenuList)
		{
			String id = menu.getStr("MENU_ID");
			String name = menu.getStr("MENU_NAME");
			String value = menu.getStr("MENU_VALUE");
			String type = menu.getStr("MENU_TYPE");
			String parentId = menu.getStr("PARENT_ID");
			int level = menu.getInt("MENU_LEVEL");
			int order = menu.getInt("MENU_ORDER");

			WechatMenuBean bean = new WechatMenuBean();
			bean.setId(id);
			bean.setName(name);
			bean.setValue(value);
			bean.setType(type);
			bean.setLevel(level);
			bean.setOrder(order);

			if (level==1)
			{
				menuList.add(bean);
				menuMap.put(id,bean);
			}
			else {
				menuMap.get(parentId).getChildren().add(bean);
			}

		}

		JSONArray buttons = new JSONArray();
		for (WechatMenuBean menu:menuList) {
			JSONObject button = new JSONObject();
			button.put("name",menu.getName());
			if (menu.getChildren().size()>0)
			{
				JSONArray subButtons = new JSONArray();
				for (WechatMenuBean subMenu:menu.getChildren()) {
					JSONObject subButton = new JSONObject();
					String type = subMenu.getType();
					subButton.put("name",subMenu.getName());
					subButton.put("type",type);
					if ("view".equals(type))
					{
						subButton.put("url",subMenu.getValue());
					}
					else  if ("media_id".equals(type))
					{
						subButton.put("media_id",mediaIdMap.get(subMenu.getValue()));
					}
					subButtons.add(subButton);
				}
				button.put("sub_button",subButtons);
				buttons.add(button);
			}
		}
		menuJson.put("button",buttons);



		String menuJsonString = menuJson.toJSONString();


		ApiResult apiResult = MenuApi.createMenu(menuJsonString);
		if (apiResult.isSucceed())
			renderText(apiResult.getJson());
		else
			renderText(apiResult.getErrorMsg());

		//renderJson(menuJsonString);
	}

	private static String batchget_material_url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=";

	public void batchGetMaterial()
	{
		int offset = getParaToInt("o",0);
		int count = getParaToInt("c",2);
		String url = batchget_material_url + AccessTokenApi.getAccessTokenStr();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("type", "news");
		dataMap.put("offset", offset);
		dataMap.put("count", count);
		String jsonResult = HttpUtils.post(url, JsonUtils.toJson(dataMap));
		renderJson(jsonResult);
	}


	private Map<String ,String> getMediaIdList()
	{
		Map<String ,String> result = new HashMap<>();
		String url = batchget_material_url + AccessTokenApi.getAccessTokenStr();
		int total = 9999999;
		int count = 20;
		for (int i = 0; i==0||i*20<total;i++)
		{
			int offset = i*count;
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("type", "news");
			dataMap.put("offset", offset);
			dataMap.put("count", count);
			String jsonResult = HttpUtils.post(url, JsonUtils.toJson(dataMap));
			JSONObject newsListJson = JSON.parseObject(jsonResult);
			total = newsListJson.getInteger("total_count");
			JSONArray items = newsListJson.getJSONArray("item");
			for (int j=0;j<items.size();j++)
			{
				JSONObject item = items.getJSONObject(j);
				String mediaId = item.getString("media_id");
				String title = item.getJSONObject("content").getJSONArray("news_item").getJSONObject(0).getString("title");
				result.put(title,mediaId);
			}
		}
		return result;
	}




	/**
	 * 获取公众号关注用户
	 */
	public void getFollowers()
	{
		ApiResult apiResult = UserApi.getFollows();
		renderText(apiResult.getJson());
	}

	/**
	 * 获取用户信息
	 */
	public void getUserInfo()
	{
		String openId = this.getRequest().getParameter("openid");
		ApiResult apiResult = UserApi.getUserInfo(openId);
		String jsonString = apiResult.getJson();
		renderText(jsonString);
	}

	public void getWxUserInfo()
	{
		String openId = this.getRequest().getParameter("openid");
		ApiResult apiResult = UserApi.getUserInfo(openId);
		String jsonString = apiResult.getJson();
		JSONObject jsonObject = JSONObject.parseObject(jsonString);
		JSONObject result = new JSONObject();
		String nickname = jsonObject.getString("nickname");
		String headimgurl = jsonObject.getString("headimgurl");

		renderJson("{openid:'"+openId+"',nickname:'"+nickname+"',headimgurl:'"+headimgurl+"'}");
	}


	/**
	 * 发送模板消息
	 */
	public void sendMsg()
	{
		String str = " {\n" +
				"           \"touser\":\"ohbweuNYB_heu_buiBWZtwgi4xzU\",\n" +
				"           \"template_id\":\"9SIa8ph1403NEM3qk3z9-go-p4kBMeh-HGepQZVdA7w\",\n" +
				"           \"url\":\"http://www.sina.com\",\n" +
				"           \"topcolor\":\"#FF0000\",\n" +
				"           \"data\":{\n" +
				"                   \"first\": {\n" +
				"                       \"value\":\"恭喜你购买成功！\",\n" +
				"                       \"color\":\"#173177\"\n" +
				"                   },\n" +
				"                   \"keyword1\":{\n" +
				"                       \"value\":\"去哪儿网发的酒店红包（1个）\",\n" +
				"                       \"color\":\"#173177\"\n" +
				"                   },\n" +
				"                   \"keyword2\":{\n" +
				"                       \"value\":\"1元\",\n" +
				"                       \"color\":\"#173177\"\n" +
				"                   },\n" +
				"                   \"remark\":{\n" +
				"                       \"value\":\"欢迎再次购买！\",\n" +
				"                       \"color\":\"#173177\"\n" +
				"                   }\n" +
				"           }\n" +
				"       }";
		ApiResult apiResult = TemplateMsgApi.send(str);
		renderText(apiResult.getJson());
	}

	/**
	 * 获取参数二维码
	 */
	public void getQrcode()
	{
		String sceneId = this.getRequest().getParameter("scene_id");
		String str = "{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": "+sceneId+"}}}";
		ApiResult apiResult = QrcodeApi.create(str);
		renderText(apiResult.getJson());

//        String str = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"123\"}}}";
//        ApiResult apiResult = QrcodeApi.create(str);
//        renderText(apiResult.getJson());
	}

	public void getQrcodeResult()
    {
        String sceneId = this.getRequest().getParameter("scene_id");
        String openId = Contant.QR_CODE_MAP.get(sceneId);
        if (openId!=null)
        {
            Contant.QR_CODE_MAP.remove(sceneId);
        }
        else {
            openId = "null";
        }
        renderText(openId);
    }

	/**
	 * 测试输出的结果
	 * create>>{"ticket":"gQFo8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL0cwT21FZjNtM3RXbmd3REF6Ml82AAIEzyFQVwMEAAAAAA==","url":"http:\/\/weixin.qq.com\/q\/G0OmEf3m3tWngwDAz2_6"}
 qrcodeUrl:https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFo8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL0cwT21FZjNtM3RXbmd3REF6Ml82AAIEzyFQVwMEAAAAAA==
	 * 
	 * 
	 */
	public void getQrcode2(){
		ApiResult apiResult = QrcodeApi.createPermanent(100);
		String qrcodeUrl = QrcodeApi.getShowQrcodeUrl(apiResult.getStr("ticket"));
		renderText("create>>"+apiResult.getJson()+" qrcodeUrl:"+qrcodeUrl);
	}

	/**
	 * 长链接转成短链接
	 */
	public void getShorturl()
	{
		String str = "{\"action\":\"long2short\"," +
				"\"long_url\":\"http://wap.koudaitong.com/v2/showcase/goods?alias=128wi9shh&spm=h56083&redirect_count=1\"}";
		ApiResult apiResult = ShorturlApi.getShorturl(str);
		renderText(apiResult.getJson());
	}

	/**
	 * 获取客服聊天记录
	 */
	public void getRecord()
	{
		String str = "{\n" +
				"    \"endtime\" : 987654321,\n" +
				"    \"pageindex\" : 1,\n" +
				"    \"pagesize\" : 10,\n" +
				"    \"starttime\" : 123456789\n" +
				" }";
		ApiResult apiResult = CustomServiceApi.getRecord(str);
		renderText(apiResult.getJson());
	}

	/**
	 * 获取微信服务器IP地址
	 */
	public void getCallbackIp()
	{
		ApiResult apiResult = CallbackIpApi.getCallbackIp();
		renderText(apiResult.getJson());
	}
	
}

